﻿/**

 * Copyright (c) 2015-2016, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */


using OF.DistributeService.Core.Client;
using OF.DistributeService.Core.Common;
using OF.DistributeService.Core.Entity;
using OF.DistributeService.Server.Service;
using System;
using System.Web.Http;
using System.Threading;
using System.Threading.Tasks;

namespace OF.DistributeService.Server
{
    public class WebApiApplicationBase : System.Web.HttpApplication
    {        
        public static OFDistributeServiceManager ServiceManager = null;
        protected void OnApplicationStart()
        {
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += (sender, args) => Util.LogException("UnobservedTaskException", args.Exception);
            try
            {
                ServiceManager = OFDistributeServiceManager.GetManager();
                ServiceManager.Startup();
            }
            catch (System.Exception ex)
            {
                Util.LogException("Application_Start", ex);
                throw;
            }
        }

        private void DoDispose()
        {
            if (ServiceManager != null)
            {
                ServiceManager.Dispose();
                ServiceManager = null;
            }
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Util.LogException("CurrentDomain_UnhandledException", e.ExceptionObject as Exception);
        }

        void CurrentDomain_DomainUnload(object sender, EventArgs e)
        {
            DoDispose();   
        }

        protected void OnApplicationEnd()
        {
            DoDispose();
        }
    }
}
